/*
Copyright (c) 2008 Nikhil Belsare

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package in.belsare.scheduler;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.List;

import com.jtheory.jdring.AlarmEntry;


class SchedulerSocketCommandInterface extends Thread {
	final private static SchedulerLogger logger = SchedulerLogger.getInstance();

	final public static int MONITOR_ACCEPT_SOCKET_WAIT_TIMEOUT = 5000;	

	private ServerSocket socket;
	private JavaScheduler scheduler; 
	private volatile boolean killMonitor = false;
	public static final String lineSeparator = System.getProperty("line.separator");
	private static final String helpString = "Nikhil's JavaCron" + lineSeparator +
	"------------------------------"  + lineSeparator +
	"help : shows this menu" + lineSeparator +
	"reload: reload scheduler tab" + lineSeparator +
	"list: list scheduled entries" + lineSeparator +
	"acount: count of active tasks" + lineSeparator +
	"shutdown: kill scheduler" + lineSeparator +
	"ptime: precise current time" + lineSeparator +
	"bye: terminates connection" + lineSeparator + 
	"------------------------------"  + lineSeparator +lineSeparator;			 


	public SchedulerSocketCommandInterface(JavaScheduler scheduler, int port) throws UnknownHostException, IOException {
		this.scheduler = scheduler;
		this.socket = new ServerSocket(port);
		this.socket.setSoTimeout(MONITOR_ACCEPT_SOCKET_WAIT_TIMEOUT);			
	}
	public void kill() {
		this.killMonitor = true;
	}
	public void run() {
		while(true) {
			// Exit gracefully 
			if(killMonitor) {
				notifyAll();
				return;
			}

			Socket inSock = null;			
			try {
				inSock = socket.accept();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(
								inSock.getInputStream()));
				BufferedWriter writer = new BufferedWriter(
						new OutputStreamWriter(
								inSock.getOutputStream()));
				writer.write(helpString);
				writer.write("javacron> ");
				writer.flush();				
				String line = null;
				while((line = reader.readLine()) != null) {
					if(line.equalsIgnoreCase("reload")) {
						writer.write("Reloading configuration." + lineSeparator);
						writer.flush();
						scheduler.reloadAlarms();											
					}else if(line.equalsIgnoreCase("list")) {
						List lst = scheduler.list();
						for(Object o : lst) {
							if(o instanceof AlarmEntry) {
								AlarmEntry ae = (AlarmEntry)o;
								writer.write(ae.getName());
								writer.write(" " + ae.alarmTime + lineSeparator);
							}
						}
						writer.flush();
					} else if(line.equalsIgnoreCase("shutdown")) {
						scheduler.shutdown();
						writer.write("Shutting down scheduler." + lineSeparator);
						writer.flush();
						inSock.close();
						break;
					} else if(line.equalsIgnoreCase("bye")) {
						try {
							writer.write("Bye Bye" + lineSeparator + "Thank you for using JavaCron. ");
							writer.flush();
							inSock.close();	
							break;
						}catch(IOException e) {};
					} else if(line.equalsIgnoreCase("help")) {
						writer.write(helpString);
						writer.flush();
					} else if(line.equalsIgnoreCase("ptime")) {
						writer.write(Long.toString(Calendar.getInstance().getTimeInMillis()));
						writer.flush();
					} else if(line.equalsIgnoreCase("acount")) {
						writer.write("Active tasks: " + scheduler.activeTasks());
						writer.flush();
					} else {
						writer.write("I don't know what to do with : " + line);
					}
					writer.write(lineSeparator + "javacron> ");
					writer.flush();
				}				
			}catch(SocketTimeoutException e) { 		
			}catch (Exception e) {
				logger.severe(e.getMessage());
			}finally {
				try {
					if(inSock != null)
						inSock.close();
				}catch(IOException e) {
					logger.severe(e.getMessage());	
				}
			}
		}
	}
}
